package com.gvitz.transaction.utils;

import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.util.Formatter;

import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;

import android.util.Base64;

public class EncriptUtils {
	
	  public static String CreateKey(String pass, String email) throws InvalidKeyException, SignatureException, NoSuchAlgorithmException{

		         String email_encript = email + new String(Hex.encodeHex(DigestUtils.sha1("gvitz es lo mejor del mundo y de todo el universo"))); // agregar un texto random
		         String key_mac = HMAC(email_encript,pass);
		         return key_mac.substring(0,16);

	  }
	
	
	  public static String encrypt(String value , String key)throws GeneralSecurityException {

	            byte[] raw = key.getBytes(Charset.forName("US-ASCII"));
	            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
	            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
	            cipher.init(Cipher.ENCRYPT_MODE, skeySpec,new IvParameterSpec(new byte[16]));
	            byte[] enc  = cipher.doFinal(value.getBytes(Charset.forName("US-ASCII")));
	            return  Base64.encodeToString(enc, Base64.DEFAULT);
	            
	  }

	  public static String HMAC(String data, String key) throws SignatureException, NoSuchAlgorithmException, InvalidKeyException{
			
		        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1");
		        Mac mac = Mac.getInstance("HmacSHA1");
		        mac.init(signingKey);
		        byte[] hmac = mac.doFinal(data.getBytes());
		               
		        Formatter formatter = new Formatter();
		      
		        for (byte b : hmac) {
				formatter.format("%02x", b);
		        }
		                  
		        return formatter.toString();
		}

}
